package com.xuan.yupao.config;

import com.xuan.yupao.common.JacksonObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.text.SimpleDateFormat;
import java.util.List;

@Configuration
 public class WebMvcConfig implements WebMvcConfigurer {


    /**
     * 处理前端时间显示问题和后端 Date 对象接收前端时间参数问题
     * @param converters 转换器
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        JacksonObjectMapper objectMapper = new JacksonObjectMapper();
        // 重写日期格式
        SimpleDateFormat smt = new SimpleDateFormat("yyyy-MM-dd");
        objectMapper.setDateFormat(smt);
        converter.setObjectMapper(objectMapper);
        converters.add(0, converter);
    }

    /**
     *  后端处理跨域问题
     * @param registry 注册表
     */
     @Override
     public void addCorsMappings(CorsRegistry registry) {
         //设置允许跨域的路径
         registry.addMapping("/**")
                 // 设置允许跨域请求的域名
                 // 当**Credentials为true时，**Origin不能为星号，需为具体的ip地址【如果接口不带cookie,ip无需设成具体ip】
//                 .allowedOrigins("http://localhost:3000","http://localhost:5173", "http://127.0.0.1:9527", "http://localhost:8080", "http://127.0.0.1:8083")
                 .allowedOriginPatterns("*")
                 // 设置允许的方法
                 .allowedMethods("*")
                 // 是否允许证书 不再默认开启
                 .allowCredentials(true)
                 // 跨域允许时间
                 .maxAge(3600);
     }


    //    @Override
//    public void addInterceptors(InterceptorRegistry registry) {
//        registry.addInterceptor(loginInterceptor)
//                .addPathPatterns("/**")
//                .excludePathPatterns("/user/login", "user/register", "/mapper/**");
//    }
}